﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Diagnostics;
using System.Globalization;

namespace ArgusLib.BugReport
{
	public static class MiniDumpWriter
	{
		const string DllName = "DbgHelp.dll";
		const string MiniDumperFile = "MiniDumper.exe";

		public static bool IsAvailable
		{
			get
			{
				try { MiniDumpWriter.ImagehlpApiVersion(); }
				catch (DllNotFoundException) { return false; }
				catch (EntryPointNotFoundException) { return false; }
				catch (BadImageFormatException) { return false; }
				return true;
			}
		}

		[DllImport(DllName)]
		private static extern IntPtr ImagehlpApiVersion();

		[DllImport(DllName)]
		public static extern bool MiniDumpWriteDump(IntPtr processHandel, int processId, IntPtr fileHandel, MinidumpType minidumpType,
			IntPtr exceptionParam, IntPtr userStreamParam, IntPtr callbackParam);

		public static bool WriteMiniDumpExtern(string file, MinidumpType minidumpType)
		{
			FileInfo dumperFile = new FileInfo(MiniDumpWriter.MiniDumperFile);
			if (IntPtr.Size == 4)
				File.WriteAllBytes(dumperFile.FullName, Resources.MiniDumper_x86);
			else if (IntPtr.Size == 8)
				File.WriteAllBytes(dumperFile.FullName, Resources.MiniDumper_x64);
			else
				return false;
			StringBuilder sb = new StringBuilder();
			Process currentProcess = Process.GetCurrentProcess();
			sb.Append(currentProcess.Handle.ToInt64().ToString(NumberFormatInfo.InvariantInfo));
			sb.Append(' ' + currentProcess.Id.ToString(NumberFormatInfo.InvariantInfo));
			sb.Append(" \"" + file + '"');
			sb.Append(' ' + ((int)minidumpType).ToString(NumberFormatInfo.InvariantInfo));
			ProcessStartInfo psi = new ProcessStartInfo(dumperFile.FullName, sb.ToString());
			psi.CreateNoWindow = true;
			Process dumperProcess = new Process();
			dumperProcess.StartInfo = psi;
			dumperProcess.Start();
			dumperProcess.WaitForExit();
			dumperFile.TryDelete();
			return dumperProcess.ExitCode == 0;
		}
	}
}
